package edu.whu.demo.security;

import edu.whu.demo.dao.UserRepository;
import edu.whu.demo.entity.Role;
import edu.whu.demo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

/**
 * 创建一个UserDetailsService的Bean，从数据库中读取用户和权限信息
 */
@Service
public class DbUserDetailService implements UserDetailsService {

    @Autowired
    UserService userService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        edu.whu.demo.entity.User user = userService.getUser(username);
        if(user == null) {
            throw new UsernameNotFoundException("User "+username +" is not found");
        }
        List<Role> rolesList = user.getRoles();
        String[] roles= new String[rolesList.size()];
        for(int i=0;i<roles.length;i++){
            roles[i]=rolesList.get(i).getName();
        }
        return User.builder()
                .username(username)
                .password(new BCryptPasswordEncoder().encode(user.getPassword()))
                //角色名直接作为权限。支持按照hasRole()或hasAnyRole()进行权限验证
                .roles(roles)
                .build();
    }
}
